package com.uroad.jilinpda.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.uroad.jilinpda.BuildConfig;
import com.uroad.jilinpda.R;
import com.uroad.jilinpda.common.BaseActivity;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.net.JsonUtil;
import com.uroad.jilinpda.util.ClipImage;
import com.uroad.jilinpda.util.FileSizeUtil;
import com.uroad.jilinpda.util.ImageUtils;
import com.uroad.jilinpda.util.ToastUtil;
import com.uroad.jilinpda.util.UIUtils;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.lib.util.check.CheckPermissionUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import org.jivesoftware.smack.util.Base64;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jzvd.JzvdStd;

/**
 * @创建者 wlw
 * @创建时间 2019/6/3 12:30
 * @描述
 */
public class OBUActivationStep2Activity extends BaseActivity {
    private String mFilePath;
    private static final int TAKE_PICTURE = 0x000003;
    @BindView(R.id.ivTrips)
    ImageView ivTrips;
    @BindView(R.id.ivObuInstall)
    ImageView ivObuInstall;
    @BindView(R.id.ivObuPlate)
    ImageView ivObuPlate;
    @BindView(R.id.tvViewExample)
    TextView tvViewExample;
    @BindView(R.id.tvViewExample2)
    TextView tvViewExample2;
    @BindView(R.id.btnNext2)
    Button btnNext2;
    @BindView(R.id.llvideo)
    LinearLayout llvideo;
    @BindView(R.id.videoTrips)
    JzvdStd videoTrips;

    CheckPermissionUtil checkPermissionUtil;
    private Map<String, String> images;
    private int selectImg;
    private String picBase64;
    private String type = "camera";
    private String orderno = "";
    private String plateno = "";
    private boolean isgm;
    private static final File PHOTO_DIR = new File(Environment
            .getExternalStorageDirectory().getAbsolutePath()+ "/DCIM/Camera");
    private File mCurrentPhotoFile;
    private Bitmap newBmp;
    private String vehtype = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_obu_activation_step_2);
        ButterKnife.bind(this);
        setTitle("标签激活");
        initData();
        initView();
//        initVedioView();
    }
    private void initVedioView() {
        videoTrips.setUp(GlobalData.obu_activation_video_url_2, "");
        videoTrips.backButton.setVisibility(View.GONE);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        videoTrips.startVideo();
    }

    @Override
    protected void onPause() {
        super.onPause();
//        Jzvd.resetAllVideos();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
//        if (Jzvd.backPress()) {
//            return;
//        }
    }

    private void initData() {
        images =new HashMap<>();
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            isgm = bundle.getBoolean("isgm");
            orderno = bundle.getString("orderno");
            vehtype = bundle.getString("vehtype");
        }
    }
    private void initView() {
        UIUtils.setViewScale(ivTrips, 670, 376);
//        UIUtils.setViewScale(llvideo, 670, 376);
        UIUtils.setViewScale(ivObuInstall, 298, 196);
        UIUtils.setViewScale(ivObuPlate, 298, 196);
    }


    @OnClick({R.id.ivObuInstall, R.id.ivObuPlate, R.id.btnNext2,R.id.tvViewExample,R.id.tvViewExample2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivObuInstall:
                selectImg = 1;
                getPhone();
                break;
            case R.id.ivObuPlate:
                selectImg = 2;
                getPhone();
                break;
            case R.id.btnNext2:
                if (TextUtils.isEmpty(images.get("1"))) {
                    ToastUtil.showShort(this,"请上传标签安装细节照片 ");
                    return;
                }
//                if (TextUtils.isEmpty(images.get("2"))) {
//                    ToastUtil.showShort(this,"请上传标签安装车辆照片");
//                    return;
//                }
                DialogHelper.showLoading(this, "正在提交");

                doRequest(ActivateWS.uploadImage1,
                        ActivateWS.uploadImage1Params(orderno, images.get("1")),
                        ActivateWS.uploadImage1);
                break;
            case R.id.tvViewExample:
                Bundle bundle = new Bundle();
                bundle.putInt("imageRes",R.mipmap.ic_obu_activation_example);
                openActivity(PhotoViewActivity.class, bundle);
                break;
            case R.id.tvViewExample2:
                Bundle bundle2 = new Bundle();
                bundle2.putInt("imageRes",R.mipmap.ic_obu_activation_example2);
                openActivity(PhotoViewActivity.class, bundle2);
                break;
        }
    }

    private void getPhone() {
        checkPermissionUtil = new CheckPermissionUtil(this, new String[]{
                Manifest.permission.CAMERA}, new CheckPermissionUtil.CheckPermissionCallBack() {
            @Override
            public void permissionAllow() {
                if (type.equals("camera"))
                    takePhoto();
                else if (type.equals("pic"))
                    goPhotoAlbum();
            }

            @Override
            public void permissionRefuse() {

            }
        });
        checkPermissionUtil.checkPermissions();
    }

    //激活相册操作
    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case CAMERA_WITH_DATA:
                    if (resultCode == 0) {
                        return;
                    }
                    setImg(mCurrentPhotoFile.getPath());
                    if (selectImg == 1) {
                        ivObuInstall.setImageBitmap(newBmp);
                        imageRecognition("1");
                    } else if (selectImg == 2) {
                        ivObuPlate.setImageBitmap(newBmp);
                        imageRecognition("2");
                    }
            }
        } else {
            showShortToast("拍照失败");
        }
    }

    private void imageFileSize(String filePath) {
        double fileOrFilesSize = FileSizeUtil.getFileOrFilesSize(filePath, 2);
        int fileSize = (int) fileOrFilesSize;
        if (fileSize > 400) {
            //图片压缩
            setImg(filePath);
        } else {
            picBase64 = ImageUtils.imageToBase64(filePath);
        }
    }

    private void setImg(String url) {
        Bitmap bmp = new ClipImage().getimage(url,600,600,400);
        newBmp = bmp;
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 90, bao);
        byte[] ba = bao.toByteArray();
        picBase64 = Base64.encodeBytes(ba);
    }


    private static final int CAMERA_WITH_DATA = 3023;

    protected void takePhoto() {
        try {
            PHOTO_DIR.mkdirs();
            mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());
            if (!mCurrentPhotoFile.exists()) {
                try {
                    mCurrentPhotoFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Intent intent = getTakePickIntent(mCurrentPhotoFile);
            startActivityForResult(intent, CAMERA_WITH_DATA);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(this, "无法启用拍照功能", Toast.LENGTH_LONG).show();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMddHHmmss");
        return dateFormat.format(date) + ".png";
    }

    public Intent getTakePickIntent(File f) {
        Uri photoUri;
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            photoUri = FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID + ".provider",f);
        }else {
            photoUri = Uri.fromFile(f);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                photoUri);
        intent.putExtra("return-data", false);
        return intent;
    }


    private void imageRecognition(String s) {
        images.put(s, picBase64);
        picBase64 = "";
    }

    @Override
    public void OnHttpTaskComplete(String result, String type) {
        super.OnHttpTaskComplete(result, type);
        DialogHelper.endLoading();
        try {
            JSONObject jsonObject = new JSONObject(result);
            if (JsonUtil.GetJsonStatu00(jsonObject)) {
                showShortToast("提交成功");
                Bundle bundle = new Bundle();
                bundle.putBoolean("isgm", isgm);
                bundle.putString("orderno", orderno);
                bundle.putString("vehtype", vehtype);
                openActivity(OBUActivationStep3Activity.class, bundle);
            }else{
                showShortToast(JsonUtil.GetErrorString(jsonObject, "msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (isFinishing() && mCurrentPhotoFile != null) {
            ImageUtils.DeletePicFromMobile(this, mCurrentPhotoFile.getPath());
        }
    }

    @Override
    public void OnHttpFailure(String msg) {
        super.OnHttpFailure(msg);
        DialogHelper.endLoading();
    }

    @Override
    public void OnHttpNetWork(String msg) {
        super.OnHttpNetWork(msg);
        DialogHelper.endLoading();
    }
}
